<template>
  <div class="approval-list-container">
    <div v-loading="navLoading" v-if="showMobilePage && showNav" :class="{'mobile-right':showMobilePage}" class="right">
      <div class="right-header pointer">
        <i class="el-icon-arrow-left mr5 ml10" @click="backNavigator"/>
        <el-dropdown trigger="click">
          <div class="el-dropdown-link menu">
            <ToolTip :content="selectItem.name" class="menu-text"/>
            <i class="el-icon-arrow-down el-icon--right"/>
          </div>
          <el-dropdown-menu slot="dropdown" class="approval-right-dropdown">
            <el-dropdown-item v-for="item in processList" :key="item.id" @click.native="changeProcessList(item.id)">{{ item.name }}</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
        <el-image v-if="showMobilePage" :src="closeIcon" class="icon close-icon" @click="setNavState(false)"/>
      </div>
      <div class="right-list">
        <ul>
          <li v-for="(item, index) in selectItem.children" :key="index" :class="{'select-bg':Number(item.id) === Number(moduleId)}" @click="changeProcess(item)">
            <ToolTip :content="item.name" />
          </li>
        </ul>
      </div>
    </div>
    <div :class="{'pc-left': !showMobilePage}" class="left">
      <el-image v-if="!showNav && showMobilePage" :src="openIcon" class="icon open-icon" @click="setNavState()"/>
      <div v-if="!showMobilePage" class="flex-center nav-wrap">
        <i class="el-icon-arrow-left mr5 ml10 pointer" @click="backNavigator"/>
        <el-cascader
          v-model="currentProcessItemId"
          :show-all-levels="false"
          :options="processList"
          :props="{
            emitPath: false,
            value: 'id',
            label: 'name',
            expandTrigger: 'hover'
          }"
          popper-class="nav-menu"
          placeholder="--"
          @change="cascaderChange"
        >
          <template slot-scope="{ data }">
            <el-tooltip v-if="data.name.length > 14" placement="top-start" effect="dark">
              <div slot="content" style="max-width: 150px;">{{ data.name }}</div>
              <span class="inline-tag ellipsisOne">{{ data.name }}</span>
            </el-tooltip>
            <span v-else>{{ data.name || '--' }}</span>
          </template>
        </el-cascader>
      </div>
      <template v-if="isCustom">
        <ListTab
          v-model="tabStatus"
          :show-header="!showMobilePage"
          :tabs="tabs"
          is-table
          @tabClick="handleTabClick"/>
        <div :class="{'mobile-table mobile-min-height':showMobilePage, 'card-class': isCard}" class="min-fill-page approval-list-content">
          <div v-if="!showMobilePage" class="filter-box">
            <FilterInput
              v-if="!switchFlag"
              ref="FilterToolRef"
              v-model="paramsObj"
              :filter-list="filterList"
              show-search-btn
              is-show-config
              @handelClick="queryClick"
              @queryEmpty="queryEmpty"
              @filterTagStatus="filterTagStatus" />
            <div v-if="hasEffectCardConfig" class="view-model">
              <el-tooltip :open-delay="800" placement="top" effect="dark" content="列表视图">
                <el-image :src="isCard ? listIcon : listIconActive" class="item" @click="viewChange(false)"/>
              </el-tooltip>
              <el-tooltip :open-delay="800" placement="top" effect="dark" content="卡片视图">
                <el-image :src="!isCard ? cardIcon : cardIconActive" class="item" @click="viewChange(true)"/>
              </el-tooltip>
            </div>
            <div v-if="!showMixedChecked" class="current-user-action-box">
              <el-checkbox v-model="isMyPending" style="margin-right: 20px;" @change="queryClick">待我处理</el-checkbox>
              <el-checkbox v-model="isShowMe" @change="queryClick" >我发起的</el-checkbox>
              <el-checkbox v-model="isMyApproval" @change="queryClick" >我审批的</el-checkbox>
            </div>
            <el-dropdown v-else :hide-on-click="false" trigger="click">
              <el-button class="el-dropdown-link search-btn-style more-btn">快捷筛选<i class="el-icon-caret-bottom"/></el-button>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item>
                  <el-checkbox v-model="isMyPending" style="margin-right: 20px;" @change="queryClick">待我处理</el-checkbox>
                </el-dropdown-item>
                <el-dropdown-item>
                  <el-checkbox v-model="isShowMe" @change="queryClick" >我发起的</el-checkbox>
                </el-dropdown-item>
                <el-dropdown-item>
                  <el-checkbox v-model="isMyApproval" @change="queryClick" >我审批的</el-checkbox>
                </el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
            <MoreOpeator
              ref="moreOperateRef"
              :list="operateExportList"
              style="z-index: 1"
            />
            <createBtn v-if="canCreate && !moduleNameLoading" :text="moduleName || '新建'" style="z-index: 1;margin-left: 10px;" @click.native="toCreate"/>
          </div>
          <div class="table-list">
            <div v-loading="listLoading" style="min-height: 100px;">
              <template v-if="list.length">
                <CardView v-if="isCard" ref="CardView" key="card" :list-data="{list, cardConfig, listLoading: cardLoading, height: setTableHeight, moduleId, fieldList: cardFieldList}" :get-operate-config="getOperateConfig" @freshCardData="freshCardData" @loadMore="loadMore"/>
                <u-table
                  v-else
                  key="table"
                  ref="commonApprovalTable"
                  :data="list"
                  :height="setTableHeight"
                  :row-class-name="tableRowClassName"
                  :row-height="rowHeight()"
                  :border="true"
                  beautify-table
                  header-drag-style
                  use-virtual
                  class="fb-table"
                  element-loading-text="加载中..."
                  empty-text="暂无数据"
                  header-cell-class-name="order-data-header-cell"
                  fit
                  hightlight-current-row
                  @row-click="openDetailDrawer"
                  @select="selectTable"
                  @select-all="selectTable"
                  @sort-change="sortMethod">
                  <u-table-column :fixed="selectFixed" align="center" type="selection" width="50" />
                  <template v-for="(field, index) in listFieldList">
                    <u-table-column
                      v-if="!isCard"
                      :key="field.key"
                      :label="field.fieldName"
                      :prop="field.key"
                      :sortable="field.isSort && 'custom'"
                      :align="field.isNumber ? 'right' : 'left'"
                      :min-width="showMobilePage ? 120 : 150">
                      <template slot-scope="scope">
                        <processSn
                          :show-expedited="index === 0"
                          :is-expedited="scope.row.isExpedited"
                          :class="field.isNumber ? 'number-cell' : ''">
                          <!-- 状态 -->
                          <StatusText
                            v-if="field.key === 'status'"
                            :color="['#FFBC3D','#FD8546', '#FF4E5F', '#999', '#31CC9C','#406EFF'][scope.row.status]"
                            :text="scope.row.status | processCommonStatus" />
                          <!--流水号支持跳转-->
                          <template v-else-if="field.type === 'workflowId'">
                            <el-tooltip v-if="scope.row.content && scope.row.content[field.key]" placement="top">
                              <div slot="content" style="max-width: 200px;">
                                <span>
                                  {{ handleSnNumber(scope.row.content[field.key]) }}
                                  <el-button
                                    type="text"
                                    size="small"
                                    style="padding: 0"
                                    @click="tooltipContentCopy(handleSnNumber(scope.row.content[field.key]))"
                                  >复制</el-button>
                                </span>
                              </div>
                              <div style="cursor: pointer;color: #406EFF;" @click.stop="toDetail(scope.row)">{{ handleSnNumber(scope.row.content[field.key]) }}</div>
                            </el-tooltip>
                            <div v-else>--</div>
                          </template>
                          <!-- 链接 -->
                          <template v-else-if="field.type === 'link'">
                            <LinkElement
                              v-if="scope.row.content && scope.row.content[field.key]"
                              :link="scope.row.content[field.key].url"
                              :link-name="scope.row.content[field.key].defaultLinkName"
                              stop-propagation
                            />
                            <div v-else>--</div>
                          </template>
                          <ToolTip v-else-if="scope.row.content && (scope.row.content[field.key] || scope.row.content[field.key] === 0)" :content="handelValue(field, scope.row.content[field.key])" />
                          <div v-else>--</div>
                        </processSn>
                      </template>
                    </u-table-column>
                  </template>
                  <u-table-column :width="operateWidth" align="left" label="操作" fixed="right">
                    <template slot-scope="scope">
                      <div class="operate">
                        <div v-if="!showMobilePage" :class="{'disabled': scope.row.status === 0}" class="button-text br bold" @click.stop="toDetail(scope.row)">查看</div>
                        <MoreOpeator
                          :list="[
                            {label: '查看', handelClick: () => {toDetail(scope.row)}, auth: showMobilePage && scope.row.status !== 0},
                            {label: '复制', handelClick: () => {handleCreateNew(scope.row)}, disabled: !canCreate || scope.row.status === 0},
                            {label: '编辑', handelClick: () => {toEdit(scope.row)}, disabled: setEditDisable(scope.row)},
                            {label: '删除', handelClick: () => {handleDelete(scope.row)}, disabled: setDelDisable(scope.row)}
                          ]"
                        >
                          <div v-if="!showMobilePage" slot="button" class="button-text bold">更多<i class="el-icon-arrow-down"/></div>
                          <el-image v-else slot="button" :src="operateBtns" class="dropdown-img"/>
                        </MoreOpeator>
                      </div>
                    </template>
                  </u-table-column>
                </u-table>
              </template>
              <EmptyPlaceholder v-else slot="empty" empty-text="暂无数据" mode="table" style="padding-bottom: 0;" />
            </div>
            <el-row v-if="showMobilePage && !isCard" type="flex" justify="left">
              <el-pagination
                v-show="listTotal > 0"
                :current-page.sync="page"
                :page-size="perPage"
                :total="listTotal"
                :small="true"
                :page-sizes="[20, 50, 100, 250, 500]"
                :layout="pageLayout"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
              />
            </el-row>
            <fixed-pagination v-if="(!isCard && listTotal > 0 && !showMobilePage) || showMobilePage" :style="fixStyle">
              <template v-if="showMobilePage">
                <FilterInput
                  v-if="!switchFlag"
                  ref="FilterToolRef"
                  v-model="paramsObj"
                  :filter-list="filterList"
                  show-search-btn
                  show-mobile-icon
                  @handelClick="queryClick"
                  @queryEmpty="queryEmpty"
                  @filterTagStatus="filterTagStatus">
                  <div slot="checkGroup">
                    <el-checkbox v-model="isMyPending" style="margin-right: 20px;" @change="queryClick">待我处理</el-checkbox>
                    <el-checkbox v-model="isShowMe" @change="queryClick" >我发起的</el-checkbox>
                    <el-checkbox v-model="isMyApproval" @change="queryClick" >我审批的</el-checkbox>
                  </div>
                </FilterInput>
                <MoreOpeator
                  ref="moreOperateRef"
                  :list="operateExportList"
                  show-mobile-icon
                />
                <div v-if="hasEffectCardConfig" class="view-model">
                  <el-tooltip :open-delay="800" placement="top" effect="dark" content="列表视图">
                    <el-image :src="isCard ? listIcon : listIconActive" class="item" @click="viewChange(false)"/>
                  </el-tooltip>
                  <el-tooltip :open-delay="800" placement="top" effect="dark" content="卡片视图">
                    <el-image :src="!isCard ? cardIcon : cardIconActive" class="item" @click="viewChange(true)"/>
                  </el-tooltip>
                </div>
                <createBtn v-if="canCreate && !moduleNameLoading" :text="moduleName || '新建'" mobile-table style="z-index: 1" @click.native="toCreate"/>
              </template>
              <template v-else>
                <SelectionNum :select-item="multipleSelectionAll" @clearMixinSelection="clearMixinSelection" />
                <div style="flex: 1;" />
                <el-pagination
                  v-show="listTotal > 0"
                  :current-page.sync="page"
                  :page-size="perPage"
                  :total="listTotal"
                  :page-sizes="[20, 50, 100, 250, 500]"
                  layout="total, prev, pager, next, sizes, jumper"
                  @size-change="handleSizeChange"
                  @current-change="handleCurrentChange" />
              </template>
            </fixed-pagination>
            <ApproverChange ref="approverChangeDialog" :business-type="BUSINESS_TYPE.APPROVAL" :module-id="moduleId" :has-approver-change="hasApproverChange" :ids="curSelectedId" @changeCallBack="changeCallBack"/>
            <DiversAuditorDialog ref="auditorDialog" :can-empty="false" @handleSender="handleDiyBatchSender" />
          </div>
        </div>
      </template>
      <!-- 固定表单列表 -->
      <template v-else>
        <keep-alive>
          <component :is="typeStr"/>
        </keep-alive>
      </template>
    </div>
    <DetailDrawer ref="detailDrawer" />
  </div>
</template>

<script>
// 工具
import axios from 'axios';
import { mapState } from 'vuex';
import { showModal } from '@/utils/message';
import { processCommonStatus } from '@/filters/status';
import { PROCESS_TYPE, CONTRACT_TYPES, ROUTE_PARAMS } from '@/utils/const/process';

// 组件
import energy from '@/views/energy';
import signUp from '@/views/signUp';
import issueInvoice from '@/views/issueInvoice';
import invoiceAbandon from '@/views/invoice/abandon';
import supplier from '@/views/supplier';
import reimbursement from '@/views/reimbursement';
import payBack from '@/views/payBack';
import loan from '@/views/loan';
import arrearsTransfer from '@/views/arrearsTransfer';
import ContractManagement from '@/views/legal';
import original from '@/views/original';
import termination from '@/views/termination';
import customerAdjustment from '@/views/customerAdjustment';
import externalHarvest from '@/views/externalHarvest';
import ListTab from '@/components/ListTab';
import EmptyPlaceholder from '@/components/EmptyPlaceholder';
import createBtn from '@/components/Common/baseComponent/createBtn';
import MoreOpeator from '@/components/Common/baseComponent/moreOpeator';
import DiversAuditorDialog from '@/components/Common/auditProcess/module/diversAuditorDialog';
import LinkElement from '@/views/legal/process/components/formMake/components/linkElement';
import CardView from '@/views/approvalModule/approvalList/components/cardView';
import selectWithoutHttp from '@/components/Common/selectWithoutHttp';
import DetailDrawer from '@/views/approvalModule/approvalList/components/detailDrawer';
// api
import {
  getCommonTab,
  getCommonApprovalList,
  commonApprovalListDelete,
  getCommonApprovalFilterList,
  getCommonApprovalModuleName,
  getApprovalExportList,
  getCommonApprovalPermissions,
  getViewConfig
} from '@/api/approvalModule';
import { getDepartmentAll } from '@/api/config';
import { getProcessManagement } from '@/api/legal';
// mixins
import TableAdaptive from '@/mixins/tableAdaptive';
import tableSelections from '@/mixins/tableSelections';
import filterFun from '@/views/approvalModule/mixins/filterFun';
import mobileTable from '@/mixins/mobileTable';
import filterObjStoreMixin from '@/mixins/filterObjStore';
import closeIcon from '@/assets/mobileIcon/close.png';
import openIcon from '@/assets/mobileIcon/open.png';
import math from '@/utils/math';
import copyLink from '@/mixins/copyLink';
import schedule from '@/mixins/schedule';
import approverChange from '@/mixins/approverChange';
import { handleCreateAgain } from '../utils';
import listIcon from '@/assets/legalProcess/listIcon.png';
import listIconActive from '@/assets/legalProcess/listIconActive.png';
import cardIcon from '@/assets/legalProcess/cardIcon.png';
import cardIconActive from '@/assets/legalProcess/cardIconActive.png';

const maxLoadNumber = 1000;

export default {
  filters: {
    processCommonStatus
  },
  components: {
    termination,
    customerAdjustment,
    externalHarvest,
    energy,
    signUp,
    loan,
    payBack,
    original,
    ContractManagement,
    supplier,
    issueInvoice,
    invoiceAbandon,
    arrearsTransfer,
    reimbursement,
    ListTab,
    EmptyPlaceholder,
    createBtn,
    MoreOpeator,
    DetailDrawer,
    DiversAuditorDialog, LinkElement, selectWithoutHttp, CardView
  },
  mixins: [TableAdaptive, tableSelections, filterFun, filterObjStoreMixin, mobileTable, copyLink, schedule, approverChange],
  data() {
    return {
      isInit: false,
      listIcon, listIconActive, cardIcon, cardIconActive,
      ROUTE_PARAMS,
      closeIcon,
      openIcon,
      moduleId: '',
      moduleName: '',
      isUmyTable: true,
      tableRefName: 'commonApprovalTable', // 表格的ref名称
      idKey: 'id', // 唯一表示字段
      tabs: [],
      list: [],
      filterList: [],
      listFieldList: [],
      cardFieldList: [],
      tabStatus: -1,
      page: 1,
      perPage: 20,
      listTotal: 0,
      paramsObj: {},
      sortName: '',
      sortType: '',
      moduleNameLoading: false,
      listLoading: false,
      cardLoading: false,
      cancelToken: null,
      isShowMe: false,
      isMyApproval: false,
      isMyPending: false,
      canExport: false, // 有导出权限
      canDelete: false, // 有删除权限
      canCreate: false, // 有新建权限
      hasApproverChange: false, // 转交权限
      approvalExportList: [],
      deptTreeList: [],
      processList: [], // 流程列表
      selectItem: {
        children: []
      },
      currentProcessItem: {
        id: '',
        isCustom: true
      },
      navLoading: false,
      showNav: false,
      switchFlag: false,
      showMixedChecked: false,
      currentProcessItemId: '',
      isCard: false,
      cardConfig: {},
      hasEffectCardConfig: false,
      viewOptions: [{ value: false, label: '列表视图' }, { value: true, label: '卡片视图' }]
    };
  },
  computed: {
    ...mapState({
      'userInfo': state => state.user.userInfo,
      'opened': state => state.app.sidebar.opened,
      fixStyle() {
        if (this.showMobilePage) {
          return `width: 100%`;
        }
        return `width: calc(((100% - ${this.opened ? '324px' : '163px'}) - 32px) - 24px)`;
      },
      operateExportList() {
        if (this.canExport) { // 导出权限
          let exportList = [{
            label: '批量导出',
            exportApi: 'admin/common/approval/export',
            type: 'export',
            exportName: '导出列表数据',
            httpMethod: 'post',
            isBeforeExport: true,
            beforeExport: this.exportBeforeExport,
            refName: 'exportRef'
          }];
          this.approvalExportList.forEach(item => {
            exportList.push({
              label: '导出' + item.name,
              exportApi: 'admin/common/approval/dataTable/export',
              type: 'export',
              exportName: item.name + '数据',
              httpMethod: 'post',
              isBeforeExport: true,
              beforeExport: this.beforeTableExport(item.id),
              refName: 'exportRef' + item.id
            });
          });
          exportList = exportList.concat([
            {
              label: '批量抄送',
              handelClick: this.handleSendMsg
            },
            {
              label: '复制链接',
              handelClick: () => this.batchCopyLink(this.list)
            },
            { label: '批量转交', handelClick: () => this.handleBatchApproverChange(this.BUSINESS_TYPE.APPROVAL) }
          ]);
          return exportList;
        } else {
          return [{
            label: '批量抄送',
            handelClick: this.handleSendMsg
          }, {
            label: '复制链接',
            handelClick: () => this.batchCopyLink(this.list)
          },
          { label: '批量转交', handelClick: () => this.handleBatchApproverChange(this.BUSINESS_TYPE.APPROVAL) }
          ];
        }
      }
    }),
    statusList() {
      return [
        { value: 0, label: '草稿中' },
        { value: 1, label: '审批中' },
        { value: 2, label: '未过审' },
        { value: 3, label: '已作废' },
        { value: 4, label: '已完成' },
        { value: 5, label: '待提交' }
      ];
    },
    // 是否自定义审批列表
    isCustom() {
      return this.currentProcessItem.isCustom;
    },
    typeStr() {
      return this.ROUTE_PARAMS.get(this.currentProcessItem.type);
    },
    isFull() {
      if (!this.listTotal) return true;
      return (this.listTotal || 0) <= this.list.length || (this.page * this.perPage) >= maxLoadNumber;
    }
  },
  beforeRouteEnter(to, from, next) {
    const pageList = ['approvalModuleCreate', 'approvalModuleEdit', 'approvalModuleDetail'];
    to.meta.isChange = pageList.includes(from.name);
    to.meta.id = from.query.id;
    to.meta.isNew = from.query.isNew;
    next();
  },
  created() {
    this.isInit = true;
  },
  activated() {
    if (this.$route.meta.isChange) {
      if (!this.moduleId) {
        this.init();
      } else {
        if (this.isCard) {
          const { id, isNew } = this.$route.meta;
          isNew ? this.fetchData(true) : (id && this.$refs.CardView.freshCardData({ moduleId: this.moduleId, id: id }));
          return;
        }
        this.fetchData();
      }
      if (!this.processList || !this.processList.length) { this.getProcessList(); }
    } else {
      this.init();
      this.getProcessList();
    }
    this.getViewConfig();
  },
  mounted() {
    this.setMixedCheckedStatus();
    window.addEventListener('resize', this.setMixedCheckedStatus);
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.setMixedCheckedStatus);
  },
  methods: {
    init() {
      this.setModuleId();
      this.queryModuleName();
      this.queryPermissions();
      this.queryFilterList(true);
    },
    tooltipContentCopy(val) {
      if (!val) return;
      this.$copyText(val).then(() => {
        this.$message.success('复制成功');
      }, e => {
        console.error(e);
      });
    },
    setMixedCheckedStatus() {
      this.$nextTick(() => {
        const mainVisibleDom = document.querySelector('.approval-list-container');
        this.showMixedChecked = !!(mainVisibleDom && mainVisibleDom.offsetWidth < 1336);
      });
    },
    openDetailDrawer(row, column) {
      if (!row.id || !row.processId || !row.processTemplateId || column.label === '操作') return;
      const listParams = {
        moduleId: row.processTemplateId,
        id: row.id,
        processId: row.processId
      };
      this.$refs['detailDrawer'].openDrawer(listParams);
    },
    getDetailLink(item) {
      if (!item.status) return null;
      return `${location.origin}#/homePage/approvalModuleDetail/${this.moduleId}?id=${item.id}&processId=${item.processId}`;
    },
    setModuleId() {
      const { id } = this.$route.params;
      if (!id) {
        this.$message.warning('无法获取审批列表数据');
        return;
      }
      this.moduleId = Number(id);
    },
    handleDiyBatchSender(users) {
      this.handleBatchSender(users, this.list);
    },
    // 流程列表
    getProcessList() {
      this.navLoading = true;
      getProcessManagement({ type: 1 }).then(res => {
        this.navLoading = false;
        if (res.code !== 200) {
          this.$message.error(res.message);
          return;
        }
        let processList = res.data;
        processList = processList.filter(el => {
          return el.children && el.children.length;
        });
        processList.forEach((el, index) => {
          if (el.children && el.children.length) {
            if (el.children.find(item => Number(item.id) === Number(this.moduleId))) {
              this.selectItem = processList && processList[index];
              this.currentProcessItemId = el.children.find(item => Number(item.id) === Number(this.moduleId)).id;
            }
          }
        });
        this.processList = this.setContractModules(processList) || [];
      }).catch(err => {
        console.log(err);
        this.navLoading = false;
      });
    },
    // 将合同所有子类型合并成单个合同流程模块
    setContractModules(list) {
      if (!Array.isArray(list) || !list.length) return [];
      const contractModuleIndex = this.getContractModuleIndex(list);
      const contractProcess = { name: '合同审批', id: -1, icon: 'configIcon2', type: -1 };
      if (contractModuleIndex !== -1) {
        const contractModuleData = list[contractModuleIndex];
        const contractModuleList = contractModuleData.children || [];
        const result = contractModuleList.filter(module => !CONTRACT_TYPES.includes(module.type));
        const contractProcessList = contractModuleList.filter(module => CONTRACT_TYPES.includes(module.type)) || [];
        contractProcess.myApprovalNum = contractProcessList.length ? contractProcessList[0].myApprovalNum : 0;
        result.unshift(contractProcess);
        list[contractModuleIndex].children = result;
      }
      return list;
    },
    // 获取合同类所在分类
    getContractModuleIndex(list) {
      let findIndex = -1;
      list.forEach((item, index) => {
        item.children && item.children.forEach(module => {
          if (CONTRACT_TYPES.includes(module.type)) {
            findIndex = index;
          }
        });
      });
      return findIndex;
    },
    changeProcessList(id) {
      if (!id) return;
      const item = this.processList.find(el => el.id === id);
      this.selectItem = item || {};
      if (this.selectItem.children && this.selectItem.children.length) {
        this.changeProcess(this.selectItem.children[0], false);
      }
    },
    async changeProcess(item = {}, isModuleIdChange = false) {
      this.currentProcessItem = item;
      this.currentProcessItemId = item.id;
      this.moduleId = item.id;
      if (!this.currentProcessItem.isCustom) return;
      this.switchFlag = true;
      this.$router.push({
        name: 'approvalList',
        params: { id: item.id }
      });
      if (this.isCustom && !isModuleIdChange) await this.getViewConfig(this.moduleId);
      this.init();
      this.paramsObj = {};
      this.isShowMe = false;
      this.isMyApproval = false;
      this.isMyPending = false;
      this.clearMixinSelection();
      this.fetchData(true, isModuleIdChange);
      if (isModuleIdChange) { this.getProcessList(); }
      this.$nextTick(() => {
        this.switchFlag = false;
      });
      if (this.$refs.FilterToolRef) {
        this.$refs.FilterToolRef.presetFilterDefault();
      } else {
        const self = this;
        setTimeout(() => {
          self.$nextTick(() => {
            self.$refs.FilterToolRef.presetFilterDefault();
          });
        });
      }
    },
    cascaderChange(childrenId) {
      let selectItem = {};
      this.processList.forEach(el => {
        if (el.children.find(item => Number(item.id) === Number(childrenId))) { selectItem = el.children.find(item => Number(item.id) === Number(childrenId)); }
      });
      this.changeProcess(selectItem);
    },
    backNavigator() {
      this.$router.push({
        name: 'approvalModule'
      });
    },
    viewChange(val) {
      this.isCard = val;
      if (val) this.perPage = 20;
      this.fetchData(true);
    },
    async getViewConfig(id) {
      const res = await getViewConfig({ id: id || this.$route.params.id });
      if (res.code === 200) {
        const { hasEffectCardConfig, cardIsEnableForCurrUser } = res.data;
        this.hasEffectCardConfig = hasEffectCardConfig;
        this.isCard = !!(cardIsEnableForCurrUser && hasEffectCardConfig);
      }
    },
    getOperateConfig(key, row) {
      return {
        'view': {
          disabled: row.status === 0,
          handelClick: (row) => { this.toDetail(row); }
        },
        'copy': {
          disabled: !this.canCreate || row.status === 0,
          handelClick: (row) => { this.handleCreateNew(row); }
        },
        'edit': {
          disabled: this.setEditDisable(row),
          handelClick: (row) => { this.toEdit(row); }
        },
        'delete': {
          disabled: this.setDelDisable(row),
          handelClick: (row) => { this.handleDelete(row); }
        }
      }[key] || {};
    },
    loadMore() {
      if (!this.listLoading && !this.cardLoading && !this.isFull) {
        this.page++;
        this.fetchData();
      }
    },
    // 刷新卡片
    freshCardData({ rowData, rowId }) {
      const index = this.list.findIndex(el => el.id === rowId);
      this.$set(this.list, index, rowData);
      this.queryTabs();
    },
    // 设置页面操作对应权限
    queryModuleName() {
      this.moduleNameLoading = true;
      getCommonApprovalModuleName(this.moduleId).then(res => {
        if (res.code === 200) {
          this.moduleName = res.data.moduleName;
        }
        this.moduleNameLoading = false;
      }).catch(_ => {
        this.moduleNameLoading = false;
      });
    },
    // 设置页面操作对应权限
    queryPermissions() {
      getCommonApprovalPermissions(this.moduleId).then(res => {
        if (res.code === 200) {
          const { hasExport, hasDelete, hasCreate, hasApproverChange } = res.data;
          this.canExport = !!hasExport;
          this.canDelete = !!hasDelete;
          this.canCreate = !!hasCreate;
          this.hasApproverChange = !!hasApproverChange;
          if (this.canExport) {
            this.queryApprovalExportList();
          } else {
            this.approvalExportList = [];
          }
        }
      }).catch(_ => {
        this.approvalExportList = [];
      });
    },
    queryApprovalExportList() {
      getApprovalExportList(this.moduleId).then(res => {
        if (res.code === 200) {
          this.approvalExportList = res.data || [];
        }
      });
    },
    async queryFilterList(isInit) {
      try {
        const deptResult = await getDepartmentAll() || {};
        this.deptTreeList = deptResult.data || [];
        const filterData = await getCommonApprovalFilterList(this.moduleId) || {};
        this.filterList = this.setFilterList(filterData.data || []);
        this.$nextTick(() => {
          if (this.$refs['FilterToolRef']) this.$refs['FilterToolRef'].changeSelectKey();
        });
        if (isInit) this.fetchData(true);
      } catch (e) {
        return false;
      }
    },
    handleTabClick(id) {
      this.tabStatus = id;
      this.list = [];
      this.listTotal = 0;
      this.fetchData(true);
    },
    setEditDisable(data) {
      return !(data.status === 0 && (data.creatorId === this.userInfo.id || data.isUserAuth));
    },
    setDelDisable(data) {
      // 草稿、已作废、未过审、待提交
      const statusArr = [0, 2, 3, 5];
      // 除审批中和已完成状态且为创建人或者有删除权限
      return !(statusArr.includes(data.status) && (data.creatorId === this.userInfo.id || this.canDelete || data.isUserAuth));
    },
    queryTabs() {
      const params = this.formatParams();
      if (!params.id) { return; }
      getCommonTab(params).then(res => {
        this.tabs = res.data;
      });
    },
    fetchData(reset = false, isModuleIdChange = false) {
      if (isModuleIdChange) { this.navLoading = true; }
      if (this.cancelToken) this.cancelToken.cancel('cancel');
      const source = axios.CancelToken.source();// 用于取消请求
      this.cancelToken = source;
      this.queryTabs();
      if (reset) this.page = 1;
      if (this.isCard && this.page !== 1) {
        this.cardLoading = true;
      } else {
        this.listLoading = true;
      }
      if (this.isCard) {
        if (this.page * this.perPage > maxLoadNumber) {
          this.perPage = maxLoadNumber - ((this.page - 1) * this.perPage);
        } else {
          this.perPage = 20;
        }
      }
      const params = this.formatParams();
      if (!params.id) { return; }
      getCommonApprovalList(params, source.token).then(res => {
        this.listLoading = false;
        this.cardLoading = false;
        if (isModuleIdChange) { this.navLoading = false; }
        if (res.code === 200) {
          this.isInit = false;
          if (this.isCard && params.page !== 1) {
            const temp = res.data && res.data.item && res.data.item.list || [];
            const list = this.list;
            res.data && res.data.item && (res.data.item.list = list.concat(temp || []));
          }
          this.list = res.data && res.data.item && res.data.item.list || [];
          if (this.isCard) {
            this.cardFieldList = res.data && res.data.item && res.data.item.field || [];
          } else {
            this.listFieldList = res.data && res.data.item && res.data.item.field || [];
          }
          this.listTotal = res.data && res.data.total || 0;
          this.cardConfig = res.data && res.data.item && res.data.item.cardConfig || {};
          this.setSelectRow && this.setSelectRow(this.list);
          const moduleId = res.data.item.moduleId;
          if (moduleId && moduleId !== params.id) {
            this.changeProcess({ id: moduleId, isCustom: true }, true);
          }
        }
      }).catch(_ => {
        this.listLoading = false;
        this.cardLoading = false;
        if (isModuleIdChange) { this.navLoading = false; }
      });
    },
    sortMethod(a) {
      if (!a.order) {
        this.sortName = '';
        this.sortType = '';
      } else {
        this.sortName = a.prop;
        this.sortType = a.order === 'ascending' ? 1 : -1;
      }
      this.fetchData();
    },
    formatParams() {
      const params = this.setDynamicFilter();
      params.id = this.moduleId;
      params.tabStatus = this.tabStatus;
      params.isShowMe = this.isShowMe;
      params.isMyApproval = this.isMyApproval;
      params.isMyPending = this.isMyPending;
      params.sortName = this.sortName || '';
      params.sortType = this.sortType || '';
      params.page = this.page;
      params.perPage = this.perPage;
      params.isCard = this.isCustom ? this.isCard : false;
      return params;
    },
    exportBeforeExport() {
      const params = this.formatParams();
      if (this.multipleSelectionAll.length) {
        params.ids = this.multipleSelectionAll.map(el => el.id).join(',');
      }
      this.$refs['moreOperateRef'] && this.$refs['moreOperateRef'].btnExport(params, 'exportRef');
    },
    beforeTableExport(id) {
      return _ => {
        const params = this.formatParams();
        if (this.multipleSelectionAll.length) {
          params.ids = this.multipleSelectionAll.map(el => el.id).join();
        } else {
          params.page = 1;
          params.perPage = 0;
        }
        params.dataTableId = id;
        this.$refs['moreOperateRef'] && this.$refs['moreOperateRef'].btnExport(params, 'exportRef' + id);
      };
    },
    queryClick() {
      !this.isInit && this.fetchData(true);
    },
    queryEmpty() {
      this.paramsObj = {};
      this.isShowMe = false;
      this.isMyApproval = false;
      this.isMyPending = false;
      this.clearMixinSelection && this.clearMixinSelection();
      this.fetchData(true);
    },
    handleSizeChange(val) {
      this.perPage = val;
      this.fetchData();
    },
    handleCurrentChange(page) {
      this.page = page;
      this.fetchData();
    },
    handleDelete(row) {
      showModal('是否确定删除?').then(() => {
        commonApprovalListDelete(row.id).then(_ => {
          this.$message.success('删除成功');
          this.resetItemSelected(row.id);
          if (row.formListCard) {
            const index = this.list.findIndex(el => el.id === row.id);
            this.list.splice(index, 1);
          } else {
            this.fetchData();
          }
        });
      });
    },
    toCreate() {
      this.$router.push({
        name: 'approvalModuleCreate',
        params: { moduleId: this.moduleId }
      });
    },
    handleCreateNew(rowData) {
      if (rowData.isNewTemplate) {
        this.$router.push({
          name: 'approvalModuleEdit',
          params: { moduleId: this.moduleId },
          query: { id: rowData.id, createNew: 1, formListCard: rowData.formListCard || 0 }
        });
        return;
      }
      const createNew = () => {
        this.toCreate();
      };
      const createOld = () => {
        this.$router.push({
          name: 'approvalModuleEdit',
          params: { moduleId: this.moduleId },
          query: { id: rowData.id, createNew: 1 }
        });
      };
      handleCreateAgain(createNew, createOld, this.$createElement);
    },
    toEdit(rowData) {
      this.$router.push({
        name: 'approvalModuleEdit',
        params: { moduleId: this.moduleId },
        query: { id: rowData.id, formListCard: rowData.formListCard || 0 }
      });
    },
    toDetail(rowData) {
      if (rowData.status === 0) return;
      this.filterObjStore(PROCESS_TYPE.APPROVAL);
      this.$router.push({
        name: 'approvalModuleDetail',
        params: { moduleId: this.moduleId },
        query: { id: rowData.id, processId: rowData.processId, fromList: 1 }
      });
    },
    handelValue(field, value) {
      if (!value || !field.options) {
        if (field.type === 'input' && field.isNumber && field.isShowPercentage) {
          return math.multiply(value, 100) + '%';
        }
        return value;
      }
      const isNumberFormula = field.type === 'formulaInput' && !field.options.modeType;
      if (value && field.options && isNumberFormula || (field.type === 'input' && field.options.dataType === 'number')) {
        const precision = field.options.precision;
        if (precision || precision === 0) {
          return Number(Number(value).toFixed(precision));
        }
      }
      return value;
    },
    setNavState(state = true) {
      this.showNav = state;
    }
  }
};
</script>

<style scoped lang="scss">
.approval-list-container {
  .table-list {
    ::v-deep {
      .link-field {
        height: auto;
        line-height: unset;
      }
    }
  }
  display: -webkit-box;
  .right {
    width: 120px;
    height: 100vh;
    color: #333333;
    background: #fff;
    .right-header {
      display: flex;
      height: 48px;
      align-items: center;
      border-bottom: 1px solid #ddd;
    }
    .right-list {
      ul {
        list-style: none;
        padding: 0;
        max-height: calc(100vh - 60px);
        overflow-y: auto;
        @include scrollBar($y: auto, $width: 6px);
      }
      li {
        cursor: pointer;
        margin: 10px;
        padding: 5px;
      }
      li:hover {
        background: #EDEEF2;
      }
      .select-bg {
        background: #EDEEF2;
      }
    }
  }
  .mobile-right {
    position: absolute;
    left: 0;
    z-index: 33;
    box-shadow: 5px 0px 6px 0 rgba(221,225,234,0.5);
    ul {
      max-height: calc(100vh - 140px) !important;
    }
  }
  .icon {
    position: absolute;
    width: 27px;
    height: 27px;
    z-index: 66;
    img {
      width: 100%;
      height: 100%;
    }
  }
  .close-icon {
    right: -11px;
    top: 118px;
  }
  .open-icon {
    left: 0;
    top: 118px;
  }
  .menu {
    display: flex;
    align-items: center;
    max-width: 70px;
    flex-wrap: nowrap;
  }
  .menu-text, .left {
    flex: 1;
  }
  .pc-left {
    ::v-deep {
      .list-tab {
        padding-left: 180px !important;
      }
    }
    .nav-wrap {
      position: absolute;
      top: 0;
      left: 0;
      height: 48px;
      z-index: 2;
      ::v-deep {
        .el-cascader {
          width: 120px;
        }
        .el-input {
          display: flex;
          align-items: center;
        }
        .el-input__suffix {
          position: unset;
        }
        .el-input__inner {
          width: 120px;
          padding: 0 !important;
          border: none;
        }
      }
    }
  }
  .operate {
    display: flex;
  }
  .approval-list-content{
    margin: 16px 16px 0 16px;
    background-color: #fff;
    padding: 20px 24px 55px 24px;
    .filter-box {
      display: flex;
      margin-bottom: 16px;
      position: relative;
      .create-btn{
        height: 32px;
        font-size: 14px;
        padding: 0 15px;
      }
      .current-user-action-box {
        position: absolute;
        left: 509px;
        top: 6px;
        display:flex;
        align-items:center;
      }
    }
  }
  .card-class {
    padding-bottom: 0 !important;
    ::v-deep {
      .link-field {
        height: 32px;
        line-height: 32px;
      }
    }
  }
  .more-btn{
    width: 96px;
    height: 32px;
    padding: 0;
    font-size: 14px;
    margin-right: 10px;
  }
  .number-cell {
    display: flex;
    justify-content: flex-end;
  }
  & ::v-deep {
    .order-data-header-cell:nth-child(2) {
      .cell {
        margin-left: 16px;
      }
    }
  }
  .view-model {
    display: flex;
    align-items: center;
    justify-content: space-around;
    width: 72px;
    height: 32px;
    flex-shrink: 0;
    border: 1px solid #dddddd;
    border-radius: 4px;
    margin-right: 16px;
    .item {
      position: relative;
      width: 24px;
      height: 24px;
      overflow: unset;
      cursor: pointer;
    }
    .item:last-child::before {
      content: '';
      position: absolute;
      left: -6px;
      top: 2px;
      width: 1px;
      height: 20px;
      background: rgba(0,0,0,0.00);
      border: 1px solid #EBEEFD;
    }
  }
}
</style>
<style lang="scss">
  .approval-right-dropdown {
    max-height: 300px !important;
    overflow: auto;
    @include scrollBar($x: auto, $y: auto, $width: 6px);
  }
  .nav-menu {
    .el-scrollbar__bar {
      display: none;
    }
    .el-cascader-menu__wrap {
      height: unset;
      max-height: 80vh;
    }
  }
</style>
